import { getProfileAPI, loginAPI } from '@/api/user'
import { TOKEN_KEY } from '@/constants/KEY'
import { resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: () => {
    return {
      token: getToken() || '',
      profile: {},
      // menuList: routes
      menuList: []
    }
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    clearUserInfo(state) {
      state.token = ''
      state.profile = {}
      removeToken(TOKEN_KEY)
    },
    setProfile(state, profile) {
      state.profile = profile
    },
    setMenuList(state, filterRoutes) {
      // state.menuList = [...state.menuList, ...filterRoutes]
      state.menuList = filterRoutes
    },
    resetMenu(state) {
      // state.menuList = routes
      state.menuList = []
      resetRouter()
    }
  },
  actions: {
    async doLogin(ctx, { username, password }) {
      const res = await loginAPI({ username, password })
      ctx.commit('setToken', res.data.token)
    },
    async getProfile(ctx) {
      const res = await getProfileAPI()
      ctx.commit('setProfile', res.data)
      return res.data.permissions
    }
  }
}
